from flask import jsonify, request, render_template
from flask_login import current_user, login_required

from apps.models.gift import Gift
from apps.models.wish import Wish
from apps.view_models.book import BookViewModel, BookCollection
from apps.forms.book import SearchForm
from apps.view_models.trade import TradeViewModel
from . import web
from apps.utils.helper import word_type
from apps.spider.yushu_book import YuShuBook


@web.route('/book/<isbn>/detail')
@login_required
def book_detail(isbn):
    in_gift = False
    in_wish = False

    book = YuShuBook()
    book.search_by_isbn(isbn)
    bk = BookViewModel(book.books[0])

    if current_user.is_authenticated:
        if Gift.query.filter_by(uid=current_user.id, isbn=isbn, launched=False).first():
            in_gift = True
        if Wish.query.filter_by(uid=current_user.id, isbn=isbn, launched=False).first():
            in_wish = True

    gifts = Gift.query.filter_by(isbn=isbn, launched=False).all()
    wishes = Wish.query.filter_by(isbn=isbn, launched=False).all()

    gifts = TradeViewModel(gifts)
    wishes = TradeViewModel(wishes)

    return render_template('book_detail.html', book=bk, wishes=wishes, gifts=gifts, in_wish=in_wish, in_gift=in_gift)


@web.route('/book/search/')
def search():
    form = SearchForm(request.args)
    books = BookCollection()
    if form.validate():
        word = form.word.data
        page = form.page.data
        wtype = word_type(word)
        yushu_book = YuShuBook()
        if wtype == 'keyword':
            yushu_book.search_by_word(word, page)
        else:
            yushu_book.search_by_isbn(word)
        books.fill(yushu_book, word)
    #     return json.dumps(books, default=lambda x:x.__dict__)
    # return form.errors
    return render_template('search_result.html', books=books)
